import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Article } from './article.entity';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private articleRepository: Repository<Article>,
  ) {}

  async findAll(): Promise<Article[]> {
    return await this.articleRepository.find();
  }

  async findOne(id: number): Promise<Article | null> {
    return await this.articleRepository.findOne({ where: { id } });
  }

  async findByCategory(categoryId: number): Promise<Article[]> {
    return await this.articleRepository.find({ where: { categoryId } });
  }

  async findByAuthor(authorId: number): Promise<Article[]> {
    return await this.articleRepository.find({ where: { authorId } });
  }

  async create(articleData: Partial<Article>): Promise<Article> {
    const article = this.articleRepository.create(articleData);
    return await this.articleRepository.save(article);
  }

  async update(id: number, articleData: Partial<Article>): Promise<Article | null> {
    await this.articleRepository.update(id, articleData);
    return await this.articleRepository.findOne({ where: { id } });
  }

  async remove(id: number): Promise<void> {
    await this.articleRepository.delete(id);
  }

  /**
   * 发布文章
   * @param id 文章ID
   */
  async publish(id: number): Promise<Article | null> {
    const article = await this.findOne(id);
    if (article) {
      article.status = 1;
      article.publishTime = new Date();
      return await this.articleRepository.save(article);
    }
    return null;
  }

  /**
   * 下架文章
   * @param id 文章ID
   */
  async unpublish(id: number): Promise<Article | null> {
    const article = await this.findOne(id);
    if (article) {
      article.status = 2;
      return await this.articleRepository.save(article);
    }
    return null;
  }
}